package com.dtsmoll.selectpicture;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.dtsmoll.permissions.PermissionsUtils;

import java.io.File;
import java.util.Objects;

public class SelectPicturesActivity extends AppCompatActivity {

    private final int SELECT_PICTURES = 0;
    private final int PHOTOGRAPH = 1;
    private final int CUT_PICTURES = 2;
    private String cameraFilePath;
    private String cropFilePath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cameraFilePath = Objects.requireNonNull(getExternalCacheDir()).getPath() + File.separator + System.currentTimeMillis() + ".jpg";
        checkSelfPermission();
    }

    // 判断权限
    private void checkSelfPermission() {
        PermissionsUtils.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA}, new PermissionsUtils.OnPermissionsCallback() {
            @Override
            public void onCallback(boolean status) {
                if (status) { // 权限获取
                    selectPhoto();
                } else { // 没有权限
                    SelectPicturesUtils.callback.onComplete("error", null);
                    finish();
                }
            }
        });
    }

    // 选择图片
    private void selectPhoto() {
        if (SelectPicturesUtils.type == SelectPicturesUtils.ALBUM) {
            startActivityForResult(new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), SELECT_PICTURES);
        } else if (SelectPicturesUtils.type == SelectPicturesUtils.CAMERA) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
            Uri photoUri; // 传递路径
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                photoUri = FileProvider.getUriForFile(this, SelectPicturesUtils.authority, new File(cameraFilePath));
            } else {
                photoUri = Uri.fromFile(new File(cameraFilePath));
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径
            startActivityForResult(intent, PHOTOGRAPH);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            SelectPicturesUtils.callback.onComplete("cancel", "");
            finish();
            return;
        }
        switch (requestCode) {
            case PHOTOGRAPH:
            case SELECT_PICTURES:
                if (SelectPicturesUtils.isCrop) {
                    cropFilePath = Objects.requireNonNull(getExternalCacheDir()).getPath() + File.separator + System.currentTimeMillis() + ".jpg";
                    File file = new File(cropFilePath);
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    Uri outputUri = Uri.fromFile(file);
                    Uri imageUri;
                    if (requestCode == PHOTOGRAPH) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            imageUri = FileProvider.getUriForFile(SelectPicturesActivity.this, SelectPicturesUtils.authority,
                                    new File(cameraFilePath));
                        } else {
                            imageUri = Uri.fromFile(new File(cameraFilePath));
                        }
                    } else {
                        if (data != null && data.getData() != null) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                imageUri = FileProvider.getUriForFile(SelectPicturesActivity.this, SelectPicturesUtils.authority,
                                        new File(SelectPicturesUtils.getImageAbsolutePath(SelectPicturesActivity.this, data.getData())));
                            } else {
                                imageUri = data.getData();
                            }
                        } else {
                            return;
                        }
                    }
                    intent.setDataAndType(imageUri, "image/*");
                    intent.putExtra("crop", "true");
                    if (SelectPicturesUtils.aspectX > 0 && SelectPicturesUtils.aspectY > 0) {
                        intent.putExtra("aspectX", SelectPicturesUtils.aspectX);
                        intent.putExtra("aspectY", SelectPicturesUtils.aspectY);
                    }
                    if (SelectPicturesUtils.outputX > 0 && SelectPicturesUtils.outputY > 0) {
                        intent.putExtra("outputX", SelectPicturesUtils.outputX);
                        intent.putExtra("outputY", SelectPicturesUtils.outputY);
                    }
                    intent.putExtra("scale", true);
                    intent.putExtra("return-data", false);
                    intent.putExtra("scaleUpIfNeeded", true);//去除黑边
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                    intent.putExtra("noFaceDetection", false);
                    startActivityForResult(intent, CUT_PICTURES);
                } else {
                    SelectPicturesUtils.callback.onComplete("success", SelectPicturesUtils.getImageAbsolutePath(SelectPicturesActivity.this, data.getData()));
                    finish();
                }
                break;
            case CUT_PICTURES:
                SelectPicturesUtils.callback.onComplete("success", cropFilePath);
                finish();
                break;
            default:
                SelectPicturesUtils.callback.onComplete("error", null);
                finish();
                break;
        }
    }
}
